package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.jeecg.modules.quartz.mapper.QuartzJobMapper;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecg.modules.system.entity.SysIndexTask;
import org.jeecg.modules.system.service.ISIndexTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author wt
 * @Date: 2024/10/11 10:44
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/sys/IndexTask")
public class IndexTaskController {
    @Autowired
    private ISIndexTaskService isIndexTaskService;
    @Autowired
    private IQuartzJobService quartzJobService;
    @Autowired
    private QuartzJobMapper quartzJobMapper;

    /**
     * 分页列表查询
     *
     * @param indexTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysIndexTask>> queryPageList(SysIndexTask indexTask,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        log.info("=====查询========"+indexTask);
        Result<IPage<SysIndexTask>> result = new Result<IPage<SysIndexTask>>();
        Page<SysIndexTask> page = new Page<SysIndexTask>(pageNo, pageSize);
        IPage<SysIndexTask> pageList = isIndexTaskService.pageisIndexTask(page, indexTask);
        result.setSuccess(true);
        result.setResult(pageList);
        log.info("=======result======" + result);
        return result;
    }

    /**
     * 新增
     *
     * @param indexTask
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysIndexTask> add(@RequestBody SysIndexTask indexTask) {
        String jsonString = "";
        log.info("=====id========"+indexTask.getId());
        log.info("=====getTaskName========"+indexTask.getTaskName());
        Result<SysIndexTask> result = new Result<SysIndexTask>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            log.info("=====网站id======" + indexTask.getWebsiteId());
            log.info("=====知识库名称======" + indexTask.getKnowledgeBase());
            log.info("=====DocIds====== " + Arrays.toString(indexTask.getDocIds()));
            if (indexTask.getTaskType()==1){
            Map<String, Object> requestMap = new LinkedHashMap<>();
            // 创建crawl_params子Map
            Map<String, Object> crawlParams = new LinkedHashMap<>();
            crawlParams.put("website_id", indexTask.getWebsiteId());
            crawlParams.put("doc_ids", Arrays.asList(indexTask.getDocIds())); // 注意这里使用List来存储数组
            // 创建job_params子Map
            Map<String, String> jobParams = new LinkedHashMap<>();
            jobParams.put("bucket_name", "crawler");
            jobParams.put("folder", "origin");
            jobParams.put("suffix", "pdf");
            jobParams.put("kb", indexTask.getKnowledgeBase());
            // 将子Map添加到主Map
            requestMap.put("crawl_params", crawlParams);
            requestMap.put("job_params", jobParams);
            // 使用Jackson库将Map转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                jsonString = objectMapper.writeValueAsString(requestMap);
                log.info("=====jsonString======" + jsonString);
            } catch (Exception e) {
                log.error("Failed to convert map to JSON string", e);
                return result.error500("转换请求体为JSON失败");
            }
                indexTask.setParameter(jsonString);
          }else {
                indexTask.setParameter(indexTask.getParameter());
            }
            indexTask.setCreateBy(sysUser.getUsername());
            indexTask.setCreateTime(new Date());
            isIndexTaskService.insertIndexTask(indexTask);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param indexTask
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysIndexTask> edit(@RequestBody SysIndexTask indexTask) {
        String jsonString = "";
        Result<SysIndexTask> result = new Result<SysIndexTask>();
            try {
                if (indexTask.getTaskType() == 1) {
                    Map<String, Object> requestMap = new LinkedHashMap<>();
                    // 创建crawl_params子Map
                    Map<String, Object> crawlParams = new LinkedHashMap<>();
                    crawlParams.put("website_id", indexTask.getWebsiteId());
                    crawlParams.put("doc_ids", Arrays.asList(indexTask.getDocIds())); // 注意这里使用List来存储数组
                    // 创建job_params子Map
                    Map<String, String> jobParams = new LinkedHashMap<>();
                    jobParams.put("bucket_name", "crawler");
                    jobParams.put("folder", "origin");
                    jobParams.put("suffix", "pdf");
                    jobParams.put("kb", indexTask.getKnowledgeBase());
                    // 将子Map添加到主Map
                    requestMap.put("crawl_params", crawlParams);
                    requestMap.put("job_params", jobParams);
                    // 使用Jackson库将Map转换为JSON字符串
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        jsonString = objectMapper.writeValueAsString(requestMap);
                        log.info("======jsonString======" + jsonString);
                    } catch (Exception e) {
                        log.error("Failed to convert map to JSON string", e);
                        return result.error500("转换请求体为JSON失败!");
                    }
                    indexTask.setParameter(jsonString);
                }else {
                    indexTask.setParameter(indexTask.getParameter());
                }
                log.info("=====修改参数值======" + indexTask.getParameter());
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                indexTask.setUpdateBy(sysUser.getUsername());
                indexTask.setUpdateTime(new Date());
                boolean ok = isIndexTaskService.editSysIndexTask(indexTask);
                if (ok) {
                    QuartzJob quartzJob = quartzJobService.selectQuartzJobTaskId(Long.valueOf(indexTask.getId()));
                    log.info("=====job查询======" + quartzJob);
                    if (quartzJob!= null) {
                        log.info("=====quartzJob======" + quartzJob.getParameter());
                        quartzJob.setParameter(indexTask.getParameter());
                        quartzJobMapper.updateQuartzJob(quartzJob);
                    }
                    result.success("修改成功!");
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("操作失败！");
            }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) throws IOException {
        isIndexTaskService.deleteWebsite(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysIndexTask> deleteBatch(@RequestParam Long[] ids) {
        Result<SysIndexTask> result = new Result<SysIndexTask>();
        if (oConvertUtils.isEmpty(ids)) {
            result.error500("未选中索引！");
        } else {
            isIndexTaskService.deleteBatchWebsite(ids);
            result.success("删除成功!");
        }
        return result;
    }

}
